﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;
using System.Collections.Specialized;
using System.Collections;

namespace System.Collections.Specialized
{
    public static class NameValueCollectionHelper
    {
        /// <summary>
        /// Adds to FormCollection.Get, for getting same Key name, when using an expresion.
        /// EX: @Html.HiddenFor(model => model.Id)
        ///     FormCollection.Get(model => model.Id)
        ///     The above would return the value for hidden form data.
        /// </summary>
        /// <typeparam name="T">The type of the members of values.</typeparam>
        /// <param name="NameColObj">The collection</param>
        /// <param name="expression">Expression to lookup</param>
        /// <returns>value of the expression data.</returns>
        public static string Get<TModel>(this NameValueCollection NameColObj, Expression<Func<TModel, object>> expression)
        {
            if (NameColObj.isNull()) return String.Empty;
            string strLookup = String.Empty;

            if (expression.Body is MemberExpression)
            {
                var body = expression.Body.ToType<MemberExpression>();
                strLookup = body.Member.Name;
            }
            else
            {
                var op = expression.Body.ToType<UnaryExpression>().Operand;
                strLookup = op.ToType<MemberExpression>().Member.Name;
            }
            return NameColObj.Get(strLookup);
        }
    }
}
